<template>
    <fs-page>
        <div class="performance-stats mb-4">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>本月销售总额</span>
                            </div>
                        </template>
                        <div class="card-content">
                            <h2>¥{{ monthlyTotal?.toLocaleString() || 0 }}</h2>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>年度销售总额</span>
                            </div>
                        </template>
                        <div class="card-content">
                            <h2>¥{{ yearlyTotal?.toLocaleString() || 0 }}</h2>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>本月目标完成率</span>
                            </div>
                        </template>
                        <div class="card-content">
                            <h2>{{ monthlyRate || 0 }}%</h2>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>年度目标完成率</span>
                            </div>
                        </template>
                        <div class="card-content">
                            <h2>{{ yearlyRate || 0 }}%</h2>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <fs-crud ref="crudRef" v-bind="crudBinding">
            <template #actionbar-right>
                <importExcel api="api/sales/performance/" v-auth="'SalesPerformanceModelViewSet:Import'">导入</importExcel>
            </template>
        </fs-crud>
    </fs-page>
</template>

<script lang="ts">
import { defineComponent, onMounted, getCurrentInstance, ref, watch } from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import createCrudOptions from './crud';
import importExcel from '/@/components/importExcel/index.vue';
import * as api from './api';

export default defineComponent({
    name: "SalesPerformance",
    components: { importExcel },
    setup() {
        const instance = getCurrentInstance();
        const context: any = {
            componentName: instance?.type.name
        };

        const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions, context });
        const monthlyTotal = ref(0);
        const yearlyTotal = ref(0);
        const monthlyRate = ref(0);
        const yearlyRate = ref(0);

        const calculateStats = (data: any[]) => {
            const now = new Date();
            const currentMonth = now.getMonth() + 1;
            const currentYear = now.getFullYear();

            // 计算本月数据
            const monthlyData = data.filter((item: any) => {
                const date = new Date(item.period);
                return date.getMonth() + 1 === currentMonth && date.getFullYear() === currentYear;
            });
            
            const monthlyActualTotal = monthlyData.reduce((sum: number, item: any) => sum + Number(item.actual_amount || 0), 0);
            const monthlyTargetTotal = monthlyData.reduce((sum: number, item: any) => sum + Number(item.target_amount || 0), 0);
            
            monthlyTotal.value = monthlyActualTotal;
            monthlyRate.value = monthlyTargetTotal > 0 ? Number(((monthlyActualTotal / monthlyTargetTotal) * 100).toFixed(2)) : 0;

            // 计算年度数据
            const yearlyData = data.filter((item: any) => {
                const date = new Date(item.period);
                return date.getFullYear() === currentYear;
            });
            
            const yearlyActualTotal = yearlyData.reduce((sum: number, item: any) => sum + Number(item.actual_amount || 0), 0);
            const yearlyTargetTotal = yearlyData.reduce((sum: number, item: any) => sum + Number(item.target_amount || 0), 0);
            
            yearlyTotal.value = yearlyActualTotal;
            yearlyRate.value = yearlyTargetTotal > 0 ? Number(((yearlyActualTotal / yearlyTargetTotal) * 100).toFixed(2)) : 0;
        };

        const loadStats = async () => {
            try {
                const res = await api.GetList({
                    page: 1,
                    limit: 9999,
                    ordering: '-period'
                });
                if (res.data) {
                    calculateStats(res.data);
                }
            } catch (error) {
                console.error('加载统计数据失败:', error);
            }
        };

        // 监听表格数据变化，重新计算统计数据
        watch(() => crudBinding.value?.data, (newData) => {
            if (newData) {
                calculateStats(newData);
            }
        }, { deep: true });

        onMounted(() => {
            crudExpose.doRefresh();
            loadStats();
        });

        return {
            crudBinding,
            crudRef,
            monthlyTotal,
            yearlyTotal,
            monthlyRate,
            yearlyRate
        };
    }
});
</script>

<style scoped>
.performance-stats {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-content {
    text-align: center;
}

.card-content h2 {
    margin: 0;
    color: #409EFF;
}
</style> 